<template>
    <div >
      <a-drawer
      width="1100"
      :maskClosable="false"
      :visible="dialogData.show"
      direction="rtl"
      @close="handleClose">
        <div slot="title">
          <span>{{dialogData.title}}</span>
        </div>
        <el-row style="padding-bottom:150px;height:100%;overflow-y:auto">
          <el-col :span="18">
             <el-form :model="parames" size="small" :rules="rules" label-position="left" ref="parames" label-width="94px" class="addForm">
                <el-row style="padding: 0 40px">
                  <a-collapse :defaultActiveKey="activeNames" :bordered="false">
                    <a-collapse-panel class="marginB10" header="基本信息" key="1">
                      <el-col :span="12" style="margin-top:15px">
                        <!-- <el-form-item label="单号:">
                          <el-input size="small" v-model="parames.receiptNumber" placeholder="请输入"></el-input>
                        </el-form-item> -->
                        <el-form-item label="收款账户:" prop="receiptAccountId">
                          <el-select style="width:100%" v-model="parames.receiptAccountId" placeholder="请选择">
                            <el-option v-for="(item,index) in accountData" :key="index" :label="item.accountName" :value="item.id"></el-option>
                          </el-select>
                        </el-form-item>
                        <el-form-item label="付款方式:" prop="paymentAccountType">
                          <el-select style="width:100%" v-model="parames.paymentAccountType" placeholder="请选择">
                            <el-option v-for="(item,index) in fukuanData" :key="index" :label="item.desc" :value="item.name"></el-option>
                          </el-select>
                        </el-form-item>
                        <el-form-item label="付款账户:" prop="paymentAccountName" :class="parames.paymentAccountType == 'BANK'?'is-required':''">
                          <el-input size="small" v-model="parames.paymentAccountName" placeholder="请输入"></el-input>
                        </el-form-item>
                        <el-form-item label="缴费日期:" prop="receiptDate">
                            <el-date-picker
                            style="width:100%"
                            v-model="parames.receiptDate"
                            type="date"
                            placeholder="选择日期">
                            </el-date-picker>
                        </el-form-item>
                        <el-form-item label="缴费开始日期:" prop="receiptStartDate" label-width="130">
                            <el-date-picker
                            v-model="parames.receiptStartDate"
                            type="date"
                            placeholder="选择日期">
                            </el-date-picker>
                        </el-form-item>
                        <el-form-item label="缴费截止日期:" prop="receiptEndDate" label-width="140">
                            <el-date-picker
                            v-model="parames.receiptEndDate"
                            type="date"
                            placeholder="选择日期">
                            </el-date-picker>
                        </el-form-item>
                      </el-col>
                      <el-col :span="16">
                        <el-form-item label="备注信息:">
                          <el-input size="small" type="textarea" v-model="parames.remark" placeholder="请输入"></el-input>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="收款凭证:">
                          <el-upload
                            class="upload-demo"
                            multiple
                            :headers="myHeaders"
                            :action="fileAction"
                            :on-success="handleSucess"
                            :on-remove="handleRemove"
                            :file-list="file">
                            <el-button icon="el-icon-upload2" type="primary" plain style="width: 400px">点击上传</el-button>
                          </el-upload>
                        </el-form-item>
                      </el-col>
                    </a-collapse-panel>
                    <a-collapse-panel class="marginB10" header="收款明细" key="2">
                      <el-col :span="24" style="margin-top:15px">
                        <el-row id="addHet" type="flex" style="padding: 0 15px">
                          <el-col :span="4">产品名称</el-col>
                          <el-col :span="4">剩余待收</el-col>
                          <el-col :span="4">本次收款</el-col>
                          <el-col :span="4">赠送数量</el-col>
                          <el-col :span="4">合同开始时间</el-col>
                          <el-col :span="4">合同结束时间</el-col>
                          <el-col :span="4">上次缴费时间</el-col>
                        </el-row>
                        <el-row>
                          <el-col :span="24" style="margin-top:15px">
                            <a-collapse :defaultActiveKey="tableKeys" :bordered="false">
                              <a-collapse-panel :key="index" :style="customStyle" v-for="(item,index) in parames.receiptDetailList">
                                <div style="background:#fafafa;margin-left:14px" slot="header">
                                  <el-row>
                                    <el-col :span="11">
                                      <span>合同流水号:</span>
                                      <span>{{item.id}}</span>
                                    </el-col>
                                    <el-col :span="9">
                                      <span>公司名称:</span>
                                      <span>{{item.customerName}}</span>
                                    </el-col>
                                    <el-col :span="2" style="text-align:right">
                                      <span class="el-dropdown-link">
                                        <a-icon style="margin: 0 15px;" type="delete" @click="handleDelproduct(index,item)"/>
                                      </span>
                                    </el-col>
                                  </el-row>
                                </div>
                                <el-row style="padding: 15px" type="flex" v-for="(itemp,indexp) in item.contractProductVOList" :key="indexp">
                                  <el-col :span="4">
                                    <span style="margin-left:15px">{{itemp.productName}}</span>
                                  </el-col>
                                  <el-col :span="4">
                                    <p>{{itemp.remainingAmount}}</p>
                                  </el-col>
                                  <el-col :span="4">
                                      <el-input style="width:80px" v-model.number="itemp.receiptAmount" @blur="handleBlur(itemp)" placeholder="请输入" size="small"></el-input>
                                      <p style="color:#f00" v-if="itemp.receiptAmount>itemp.remainingAmount">输入金额不能超过剩余待收</p>
                                  </el-col>
                                  <el-col :span="4">
                                    <p>{{itemp.giftCount}}</p>
                                  </el-col>
                                  <el-col :span="4">
                                    <p>{{itemp.contractStartDate | formatDate}}</p>
                                  </el-col>
                                  <el-col :span="4">
                                    <p>{{itemp.contractEndDate | formatDate}}</p>
                                  </el-col>
                                  <el-col :span="4">
                                    <p>{{itemp.lastReceiptDate | formatDate}}</p>
                                  </el-col>
                                </el-row>
                              </a-collapse-panel>
                            </a-collapse>
                          </el-col>
                        </el-row>
                        <el-button icon="el-icon-plus" size="small" @click="handelAddProduct" style="width:100%;margin-top:20px">添加合同</el-button>
                      </el-col>
                    </a-collapse-panel>
                  </a-collapse>
                </el-row>
              </el-form>
            </el-col>
            <el-col :span="5" style="position: fixed;top:80px;right:-10px;width:240px">
              <div v-if="dialogData.type == 'edit'">
                <el-button
                  @click="handleCancle"
                  size="small"
                  icon="el-icon-close"
                  style="width:200px;text-align: left;margin-bottom:10px"
                >取消编辑</el-button>
              </div>
            </el-col>
        </el-row>
        
        <div class="from-bottom-box">
          <el-button size="small" type="primary" :loading="loadingBtn" @click="handleSave">保存</el-button>
          <el-button size="small" @click="handleClose">取消</el-button>
        </div>
      </a-drawer>
      <hetongDialog :hetongData="hetongData" @watchSlect="watchSlect"></hetongDialog>
    </div>
</template>

<script>
import hetongDialog from './addHetong'
export default {
    props: ['dialogData'],
    data() {
        return {
          customStyle: 'border-radius: 4px;margin-bottom: 8px;border: #f7f7f7 solid 1px;overflow: hidden',
          activeNames: ['1','2'],
          loadingBtn: false,
          parames: {
            id: '',
            receiptAccountId: '', //收款账户ID,
            receiptAccountName: '', //收款账号名称
            paymentAccountName: '', //付款账户,
            receiptDate: '',
            receiptStartDate: '',
            receiptEndDate: '',
            remark: '', //备注信息,
            paymentAccountType: '',
            attachmentSet:[],
            receiptDetailList:[]
          },
          tableKeys: [0,1,2,3],
          myHeaders: {authorization: ''},
          fileList: [],
          file: [],
          fileAction: this.$api.posFinanceReceiptCertificateUpload, //附件上传地址
          hetongData: {
            title: '',
            slectData: [],
            show: false
          },

          rules: {
            receiptAccountId: [{ required: true, message: '必填', trigger: ['change','blur' ]}],
            paymentAccountName: [{
              validator: (rule, value, callback) => {
                if (value === '' && this.parames.paymentAccountType == 'BANK') {
                  callback(new Error('请输入付款帐户'));
                } else {
                  callback();
                }
              },
              trigger: 'blur'
            }],
            // receiptDate: [{ required: true, message: '必填', trigger: ['blur' ]}],
            paymentAccountType: [{ required: true, message: '必填', trigger: ['change','blur' ]}],
            receiptDate: [{ required: true, message: '必填', trigger: ['blur' ]}],
            receiptStartDate: [{ required: true, message: '必填', trigger: ['blur' ]}],
            receiptEndDate: [{ required: true, message: '必填', trigger: ['blur' ]}],
          },
          fukuanData: [], //付款方式
          contactType: [], //联系方式
          importData: [], //重要程度
          urgencyData: [], //紧急程度
          accountData: [], //帐户list
          inputVisible: false,
          inputValue: ''
        };
    },
    created() {

    },
    mounted() {

    },
    methods: {
      handleClose () { //关闭弹窗
        this.dialogData.show = false
      },
      handleCancle () { //取消重新编辑
        this.dialogData.show = false
        this.$emit('checkOpen')
      },
      handleBlur (item) { //输入价格失去焦点
       var re = /^[0-9]+.?[0-9]*$/; //判断字符串是否为数字 //判断正整数 /^[1-9]+[0-9]*]*$/
    　　if (!re.test(item.price2)) {
          console.log('ttt')
    　　　　item.price2 = ''
    　　　　return false;
    　　}
      },
      handleSucess (response,fileList) { //上传附件成功返回url
        this.fileList.push({
            name: response.data.name,
            url: response.data.url
        })
      },
      handleRemove (file) { //删除附件更新
          this.fileList.forEach((el,index)=>{
              if (file.response) {
                  if (el.url == file.response.data.url) {
                      this.fileList.splice(index, 1)
                  }
              } else {
                  if (el == file.url) {
                      this.fileList.splice(index, 1)
                  }
              }
          })
      },
      watchSlect (data) { //监听返回的选中的数组
        let select = data //选中的数组
        let origan = this.parames.receiptDetailList //本身存在的数组
        select.forEach(el=>{
          let i = 0
          origan.forEach((bl,index)=>{
            if (el.id == bl.id) {
              i = 1
            }
          })
          el.contractProductVOList.forEach(bl=>{
            bl.contractStartDate = el.startDate
            bl.contractEndDate = el.endDate
            bl.lastReceiptDate = el.lastReceiptDate
          })
          if (i !== 1) {
            this.parames.receiptDetailList.push(el)
          }
        })
      },
      handleDelproduct (index,row) { //删除当前行
        this.parames.receiptDetailList.splice(index,1)
      },
      handelAddProduct () { //添加合同
        this.hetongData.title = '选择合同'
        this.hetongData.slectData = this.parames.receiptDetailList
        this.hetongData.show = true
      },
      setData () { //处理数据
        this.parames.attachmentSet = this.fileList
        let receiptDetailList = []
        this.parames.receiptDetailList.forEach(el=>{
          el.contractProductVOList.forEach(bl=>{
            if (bl.contractProductId) {
              receiptDetailList.push({
                contractProductId: bl.contractProductId,
                receiptAmount: bl.receiptAmount?bl.receiptAmount:0
              })
            } else {
              receiptDetailList.push({
                contractProductId: bl.id,
                receiptAmount: bl.receiptAmount?bl.receiptAmount:0
              })
            }
          })
        })
        this.parames.receiptDetailList = receiptDetailList
      },
      handleSave () { //保存
        this.$refs['parames'].validate((valid) => {
          if (valid) {
            if (this.parames.receiptDetailList.length == 0) {
              this.$message({
                message: '收款明细不能为空',
                type: 'warning'
              });
              return false
            }
            let i = 0
            this.parames.receiptDetailList.forEach(el=>{
              el.contractProductVOList.forEach(bl=>{
                if(bl.receiptAmount>bl.remainingAmount) {
                  i = 1
                }
              })
            })
            if (i == 1) {
              return false
            }
            this.setData()
            this.loadingBtn = true
            if (this.dialogData.type == 'edit') { //修改保存成功
              let api = ''
              if (this.dialogData.apiType == '1') {
                api = this.$api.posFinanceReceiptEdit
              } else if (this.dialogData.apiType == '2') {
                api = this.$api.posFinanceReceiptEditForConfirmed
              }
              this.$post(api,this.parames).then(response => {
                if (response.data.succeed) {
                  this.$message({ type:'success',message: '修改成功'})
                  this.handleClose()
                  this.$emit('checkOpen','1') //重新打开父级弹窗
                }
              })
            } else { //新增
              this.$post(this.$api.posFinanceReceiptAdd,this.parames).then(response => {
                if (response.data.succeed) {
                  this.$message({ type:'success',message: '保存成功'})
                  this.$emit('checkRender')
                  this.handleClose()
                }
              })
            }
            setTimeout(() => {
              this.loadingBtn = false
            }, 300);
          }
        })
      },
      render () { //获取详情信息并修改
        this.loading = true
        this.$post(this.$api.posFinanceReceiptFind,{
          receiptRecordId: this.dialogData.id
        }).then(response => {
          if (response.data.succeed) {
            let data = response.data.data
            this.parames.id = data.id
            this.parames.receiptAccountId = data.receiptAccountId
            this.parames.receiptAccountName = data.receiptAccountName
            this.parames.paymentAccountName = data.paymentAccountName
            this.parames.receiptDate = data.receiptDate
            this.parames.receiptStartDate = data.receiptStartDate
            this.parames.receiptEndDate = data.receiptEndDate
            this.parames.remark = data.remark
            if (data.paymentAccountType) {
              this.parames.paymentAccountType = data.paymentAccountType.name
            }
            let origan = data.receiptDetailList //本身产品数组
            this.parames.receiptDetailList = this.$utils.unique(origan) 
            this.parames.attachmentSet = data.attachmentSet
            this.fileList = data.attachmentSet
            data.attachmentSet.forEach(el=>{
                this.file.push({
                    name: el.name,
                    url: el.url
                })
            })
            for (var i = 0; i < origan.length; i++) {
              for (var j = 0; j < this.parames.receiptDetailList.length; j++) {
                if (origan[i].contractId == this.parames.receiptDetailList[j].id) {
                  this.parames.receiptDetailList[j].contractProductVOList.push(origan[i])
                }
              }
            }
            setTimeout(() => {
              this.loading = false
            }, 200);
          }
        })
      },
      getAccount (id) {//获取帐户数据
        this.$post(this.$api.postProviderAccountList,{
          providerId: id,
        }).then(response => {
          if (response.data.succeed) {
            this.accountData = response.data.data
          }
        })
      },
      resetData () { //重置数据
        this.parames.id = ''
        this.parames.receiptAccountId = '' //收款账户ID
        this.parames.receiptAccountName = '' //收款账号名称
        this.parames.paymentAccountName = '' //付款账户
        this.parames.receiptDate = ''
        this.parames.remark = '' //备注信息
        this.parames.receiptStartDate = ''
        this.parames.receiptEndDate = ''
        this.parames.paymentAccountType = ''
        this.parames.attachmentSet = []
        this.parames.receiptDetailList = []
        this.fileList = []
        this.file = []
        this.$refs.parames.resetFields()
      }
    },
    components: {
      hetongDialog
    },
    computed: {
      changeDialog () {
        return this.dialogData.show
      }
    }, 
    watch: {
      changeDialog: {
        handler (curVal, oldVal) {
          if (curVal) {
            this.$utils.getEnumberation('postProviderAccountType','fukuanData',this) //付款方式
            this.myHeaders.authorization = this.$utils.getLocalStorage('usertoken')
            let companyId = this.$utils.getLocalStorage('user').companyId
            this.getAccount(companyId)
            if (this.dialogData.type == 'edit') {
              this.render()
            }
          } else {
            this.resetData()
          }
        }
      }
    },
};
</script>

<style>
#addHet .ant-collapse > .ant-collapse-item > .ant-collapse-header .ant-collapse-arrow{
  left: 15px;
}
#addHet .ant-collapse > .ant-collapse-item > .ant-collapse-header{
  background: #fafafa;
}
#addHet .ant-collapse > .ant-collapse-item{
  border-bottom: #f7f7f7 solid 1px!important;
}
</style>
